package net.zjitc.controller;

import net.zjitc.common.ResponseResult;
import net.zjitc.common.lang.Const;
import net.zjitc.entity.ImgUpload;
import net.zjitc.utils.ThumbnailsUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author 毛钰深
 * @create 2022/1/12
 */
@RestController
public class ImgUploadController {

    /**
     * 初始化判断D盘下的upload文件夹是否存在,不存在则创建
     */
    @PostConstruct
    public void init() {
        File dir = new File("D:/upload");
        if (dir.exists()) {
            if (!dir.isDirectory()) {
                boolean mkdir = dir.mkdir();
                if (mkdir) {
                    System.out.println("在D盘下创建一个新的upload文件夹");
                }
            } else {
                System.out.println("文件夹已经存在");
            }
        } else {
            boolean mkdir = dir.mkdir();
            if (mkdir) {
                System.out.println("在D盘下创建一个新的upload文件夹");
            }
        }
    }

    /**
     * 暂时是图片上传即保存,后续需要修改前端页面和后台此处的代码,修改为点击按钮再上传图片
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAuthority('162')")
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file, HttpServletRequest request) throws Exception {
        ResponseResult res = new ResponseResult();
        //重命名文件名称
        String filename = file.getOriginalFilename();
        filename = System.currentTimeMillis() + "_" + filename;

        //获取上传图片的类型
        String[] split = filename.split("\\.");
        String type = split[split.length - 1];

        //传入图片类型转换
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getBytes()));

        //保存到D盘下的upload目录中
        //设置不同的大小并且保存到目录下
        BufferedImage imageBig = ThumbnailsUtils.resizeImageOne(image, type, 800, 800);
        BufferedImage imageMid = ThumbnailsUtils.resizeImageOne(image, type, 400, 400);
        BufferedImage imageSma = ThumbnailsUtils.resizeImageOne(image, type, 200, 200);

        //(原图或许不用,只需要保存处理后的图??)
        String imgPath = "D:/upload/" + filename;
        file.transferTo(new File(imgPath));

        String imgPathBig = "D:/upload/" + Const.IMAGE_BIG + filename;
        String imgPathMid = "D:/upload/" + Const.IMAGE_MID + filename;
        String imgPathSma = "D:/upload/" + Const.IMAGE_SMA + filename;

        ImageIO.write(imageBig, type, new File(imgPathBig));
        ImageIO.write(imageMid, type, new File(imgPathMid));
        ImageIO.write(imageSma, type, new File(imgPathSma));


        //设置上传图片保存的相对路径和网络访问路径,并且返回
        ImgUpload imgUpload = new ImgUpload();
        imgUpload.setTmp_path("upload/" + filename);

        //ip和端口判断
        int port = 8888;
        String localhost1 = "localhost";
        String localhost2 = "127.0.0.1";
        if (!localhost1.equals(request.getServerName()) && !localhost2.equals(request.getServerName())) {
            port = 50904;
        }
        //网页可以通过此url直接访问到上传的图片
        imgUpload.setUrl(request.getScheme() + "://" + request.getServerName() + ":" + port + "/api/private/v1/upload/" + filename);

        res.setSuccess("上传成功", imgUpload);
        return res;
    }
}
